package union_find_Algorithm.leetcode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 1. 问题描述
 *
 * 2. 算法分析
 *
 * 3. 代码实现
 */
@SuppressWarnings("all")
public class 不同省份 {
    class UnionFind {
        int[][] isConnected;
        int citys;
        int[] root;
        int count;  // 记录最终的省份
        int[] rank;

        public UnionFind(int[][] isConnected) {
            isConnected = isConnected;
            citys = isConnected.length;
            root = new int[citys];
            count = citys; // 初始化每个城市各自为省，所以count为城市数量
            rank = new int[citys];
            for(int i = 0; i < citys; i++) {
                root[i] = i;
                rank[i] = 1;
            }
        }

        public int find(int x) {
            if(root[x] == x) {
                return x;
            }
            return find(root[x]);
        }

        public void union(int x, int y) {
            int rootX = find(x);
            int rootY = find(y);
            if(rootX != rootY) {
                if(rank[rootX] < rank[rootY]) {
                    root[rootX] = rootY;
                }
                else if(rank[rootX] > rank[rootY]) {
                    root[rootY] = rootX;
                }
                else if(rank[rootX] == rank[rootY]) {
                    root[rootY] = rootX;
                    rank[rootX] ++;
                }
            }
        }
    }

    /**
     * 最后查看root中有多少个根节点即可
     * @param isConnected
     * @return
     */
    public int findCircleNum(int[][] isConnected) {
        if(isConnected.length == 0 || isConnected == null) {
            return 0;
        }
        UnionFind uf = new UnionFind(isConnected);
        for(int i = 0; i < isConnected.length; i++) {
            for(int j = i + 1; j < isConnected.length; j++) {
                if(isConnected[i][j] == 1) {
                    uf.union(i,j);
                }
            }
        }
        int proviences = 0;
        for(int i = 0; i < uf.root.length; i++) {
            if(uf.root[i] == i) {
                proviences++;
            }
        }
        return proviences;
    }

    public static void main(String[] args) {
        Deque<Character> deque = new ArrayDeque<>();
    }
}
